package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.model.CompanyRoyaltyModel;
import one.stand.model.ResultModel;
import one.stand.model.UserLevelModel;
import one.stand.request.UserLevelRequest;
import one.stand.response.UserLevelResponse;
import one.stand.service.BaseService;
import one.stand.service.DistributionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: ZRH
 * @CreateDate: 2019/6/20 10:45
 */
@Service
public class DistributionServiceImpl extends BaseService implements DistributionService {

    @Override
    public ResultModel<Boolean> insertUserLevel(UserLevelRequest request) {
        log.info("申请成为分销员:{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null || request.getCompanyId() == null){
            return ResultModel.checkParamFail();
        }
        CompanyRoyaltyModel companyRoyaltyModel1 = new CompanyRoyaltyModel();
        companyRoyaltyModel1.setCompanyId(request.getCompanyId());
        List<CompanyRoyaltyModel> list = companyRoyaltyMapper.select(companyRoyaltyModel1);
        if(list == null || list.size() <= 0){
            return ResultModel.fail("该企业未设置分销员~！");
        }
        List<UserLevelModel> userLevelModelList = userLevelMapper.select(new UserLevelModel(){{
            setUserId(request.getId().intValue());
            setCompanyId(request.getCompanyId());
        }});
        if(userLevelModelList != null && userLevelModelList.size() > 0){
            if(userLevelModelList.get(0).getState() == 0){
                return ResultModel.fail("请勿重复提交申请~！");
            } else if(userLevelModelList.get(0).getState() == 1){
                return ResultModel.fail("您已经是该公司的分销员~！");
            }
        }
        CompanyRoyaltyModel companyRoyaltyModel = list.get(0);
        UserLevelModel model = new UserLevelModel();
        model.setUserId(request.getId().intValue());
        model.setCompanyId(request.getCompanyId());
        model.setRoyaltyId(companyRoyaltyModel.getRoyaltyId());
        model.setCreateTime(currentDate());
        userLevelMapper.insertSelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Map<String, Object>> getUserLevelInfo(UserLevelRequest request) {
        log.info("分销员中心:{}",JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        UserLevelModel model = new UserLevelModel();
        model.setUserId(request.getId().intValue());
        UserLevelModel userLevelModel = userLevelMapper.getUserLevelInfo(request.getId().intValue());
        userLevelModel.setNickeName(StringUtils.isBlank(userLevelModel.getNickeName()) ? "" : new String(java.util.Base64.getDecoder().decode(userLevelModel.getNickeName())));
        Map<String, Object> map = new HashMap<>(2);
        map.put("userLevelModel",userLevelModel);
        map.put("newOrderCount",userLevelMapper.getNewOrderCount(request.getId().intValue()));
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Map<String, Object>> saveInvitationCard(UserLevelRequest request) {
        log.info("生成邀请卡:{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        List<UserLevelModel> list = userLevelMapper.saveInvitationCard(new UserLevelModel(){{
            setUserId(request.getId().intValue());
        }});
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        UserLevelModel model = list.get(0);
        // 公司名称
        StringBuffer buffer = new StringBuffer();
        list.forEach(obj->{{
            buffer.append("(").append(obj.getCompanyName()).append(")");
        }});
        // 公司数量
        Integer num = list.size();
        // 邀请人头像
        model.getAvatarUrl();
        // 邀请人名称
        String nickName = StringUtils.isBlank(model.getNickeName()) ? "" : new String(java.util.Base64.getDecoder().decode(model.getNickeName()));
        //todo 生成画布

        Map<String, Object> map = new HashMap<>(2);
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Boolean> saveDistributor(UserLevelRequest request) {
        log.info("邀请存为分销员(扫码进入):{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null || request.getParentId() == null){
            return ResultModel.checkParamFail();
        }
        List<UserLevelModel> list = userLevelMapper.select(new UserLevelModel(){{
            setUserId(request.getParentId());
        }});
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        for(UserLevelModel userLevelModel : list) {
            List<CompanyRoyaltyModel> companyRoyaltyModelList = companyRoyaltyMapper.select(new CompanyRoyaltyModel(){{
                setCompanyId(userLevelModel.getCompanyId());
            }});
            boolean fal = companyRoyaltyModelList == null || companyRoyaltyModelList.size() <= 0 || companyRoyaltyModelList.get(0).getRoyaltyId() == null;
            if(fal){
                continue;
            }
            userLevelModel.setUserId(request.getId().intValue());
            userLevelModel.setRoyaltyId(companyRoyaltyModelList.get(0).getRoyaltyId());
            userLevelModel.setState(0);
            userLevelModel.setLevelId(null);
            userLevelModel.setCreateTime(currentDate());
            userLevelModel.setRemark("邀请加入~！");
            userLevelModel.setParentId(request.getParentId());
            userLevelMapper.insertSelective(userLevelModel);
        }
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Map<String, Object>> myInvitationList(UserLevelRequest request) {
        log.info("我的邀请列表:{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        UserLevelModel model = new UserLevelModel();
        BeanUtils.copyProperties(request, model);
        model.setParentId(request.getId().intValue());
        List<UserLevelModel> list = userLevelMapper.myInvitationList(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        PageInfo<UserLevelModel> pageInfo = new PageInfo<>(list);
        List<UserLevelResponse> responseList = new ArrayList<>();
        pageInfo.getList().forEach(obj->{{
            UserLevelResponse response = new UserLevelResponse();
            BeanUtils.copyProperties(obj, response);
            response.setNickeName(StringUtils.isBlank(obj.getNickeName()) ? "" : new String(java.util.Base64.getDecoder().decode(obj.getNickeName())));
            responseList.add(response);
        }});
        Map<String, Object> map = new HashMap<>(2);
        map.put("list",responseList);
        map.put("total",pageInfo.getTotal());
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Map<String, Object>> applyBusinessList(UserLevelRequest request) {
        log.info("推广商家列表:{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        UserLevelModel model = new UserLevelModel();
        model.setUserId(request.getId().intValue());
        List<UserLevelModel> list = userLevelMapper.applyBusinessList(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        PageInfo<UserLevelModel> pageInfo = new PageInfo<>(list);
        List<UserLevelResponse> responseList = new ArrayList<>();
        pageInfo.getList().forEach(obj->{{
            UserLevelResponse response = new UserLevelResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        Map<String, Object> map = new HashMap<>(3);
        map.put("list",responseList);
        map.put("total",pageInfo.getTotal());
        map.put("orderMoney",userLevelMapper.getOrderMoeny(request.getId().intValue()));
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<List<UserLevelResponse>> distributorOrderList(UserLevelRequest request) {
        log.info("推广订单列表:{}", JSON.toJSONString(request));
        if(request == null || request.getId() == null){
            return ResultModel.checkParamFail();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        UserLevelModel model = new UserLevelModel();
        BeanUtils.copyProperties(request, model);
        model.setUserId(request.getId().intValue());
        model.setCompanyId(request.getCompanyId());
        List<UserLevelModel> list = userLevelMapper.distributorOrderList(model);
        if(list == null || list.size() <= 0){
            return ResultModel.noData();
        }
        PageInfo<UserLevelModel> pageInfo = new PageInfo<>(list);
        List<UserLevelResponse> responseList = new ArrayList<>();
        pageInfo.getList().forEach(obj->{{
            UserLevelResponse response = new UserLevelResponse();
            BeanUtils.copyProperties(obj, response);
            responseList.add(response);
        }});
        return ResultModel.success(responseList);
    }
}
